<?php

class Model_Cfg_Action extends Jwawa_BaseModel
{
    function __construct(&$prop_array = null)
    {
        parent::__construct($prop_array);

        if($this->parent_id === 0){
            $this->parent_id = null;
        }
    }

    public static function findAllLeafActions(){
        $sql = "SELECT ca.id, ca.action_code
            FROM cfg_actions ca
            WHERE ca.is_deleted = 'N'
            AND ca.is_leaf = 'Y'
            ORDER BY ca.action_code ";
        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->execute();
        $rst = $stmt->fetchAllObj('Model_Cfg_Action');

        return $rst;
    }

    public static function findUserActionCodeList($login_account_id)
    {
        $sql = "SELECT ca.action_code
            FROM plg_role_login_ships prls
            JOIN plg_roles pr ON pr.id = prls.plg_role_id
            JOIN plg_role_action_ships pra ON pra.plg_role_id = prls.plg_role_id
            JOIN cfg_actions ca ON ca.id = pra.plg_action_id
            WHERE prls.sso_login_account_id = :login_account_id
              AND pr.is_deleted = 'N'
              AND ca.is_deleted = 'N'";
        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->bindValue('login_account_id', $login_account_id);
        $stmt->execute();
        $rst = $stmt->fetchAll(PDO::FETCH_COLUMN);

        return $rst;
    }


    public static function getActionIdByCode($actionCode)
    {
        $sql = "SELECT ca.id
                FROM cfg_actions ca
                WHERE ca.action_code = :action_code";
        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->bindValue('action_code', $actionCode);
        $stmt->execute();
        $rst = $stmt->fetchObj();
        if(count($rst) == 1){
            return $rst->id;
        } else {
            throw new Jwawa_BusinessException('ERROR_ACTION_NOT_EXISTED', array($actionCode));
        }
    }
}
